

#import "FirstNavigationView.h"
#import "ShopListController.h"
#import "DetailShopViewController.h"
#import "ResolveXML.h"
#import "GDataXMLNode.h"
#import "AppDelegate.h"
#import "SupplierManager.h"
#import "PublicFunction.h"
#import "FMDBManager.h"
#import "FMDatabase.h"
#import "NetWorkManager.h"
#import "FMDBCollectionManager.h"
#import "FMDBTransactionHistory.h"
#import "TransactionHistory.h"
#import "UICustomImageView.h"
#import "SearchController.h"
#import "SearchShopListController.h"
#import "Ad.h"
#import "AdManager.h"
#import "UICustomImageView.h"
#import "FMDBAdManager.h"
#import "MobClick.h"
#import "Constants.h"
#define ISNULL @"1"   //1为空
@implementation FirstNavigationView
@synthesize supplierCategories;
@synthesize appDelegate;
@synthesize searchBarCustom;
@synthesize bgScrView;
@synthesize topView;
//@synthesize supplierManager;
@synthesize scrollView;
@synthesize timeCount;
@synthesize fmdbAdManager;
@synthesize adsCount;
@synthesize isTouched;
@synthesize ads;
@synthesize supIdToString;
@synthesize supTypeId;

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//加载本地nib文件
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

//初始化searchBar
-(void)initSearchBar{
    //search bar
    searchBarCustom = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    //添加文本默认内容
    searchBarCustom.placeholder=@"请输入商铺名称或菜品";
    //设置取消按钮
    searchBarCustom.showsCancelButton=YES;
    //改变searchbar颜色
    //移出原背景颜色
    UIView *segment=[searchBarCustom.subviews objectAtIndex:0];
    [segment removeFromSuperview];
    //设置背景为白色
    searchBarCustom.backgroundColor=[UIColor whiteColor];
    //修改取消按钮文字
    [self searchBarTextDidBeginEditing:searchBarCustom];
    
    //添加searchbar背景图片
    UIImageView* searchbarImg=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,44)];
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"searchBarBg-d" ofType:@"png"];
    [searchbarImg setImage:[UIImage imageWithContentsOfFile:filePath]];
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forBarMetrics: UIBarMetricsDefault];
    
    
    
    //insertSubview的时候searchbarimg的count+1
    [searchBarCustom insertSubview:searchbarImg atIndex:0];
    searchBarCustom.delegate=self;
    [self.view addSubview:searchBarCustom];
}

- (IBAction)cancelInput:(id)sender{
    
    [searchBarCustom resignFirstResponder];
    
    
}

//初始化首页滚动背景
-(void)initScrollView{
    //Scrollview
    bgScrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,39,320,415)];
    //    [bgScrView setBackgroundColor:[UIColor whiteColor]];
    //设置为滚动
    bgScrView.pagingEnabled = YES;
    //设置滚动的内容大小
    [bgScrView setContentSize:CGSizeMake(320,418)];
    //添加滚动背景
    [self.view addSubview:bgScrView];
}

//生成商铺类型按钮
-(void)setSuppierCategoryBtn:(UIView *)view{
    if([appDelegate status])
    {
        SupplierCategoryManager *manager = [[SupplierCategoryManager alloc] init];
        supplierCategories= [manager getAllSupplierCategories];
        recieveDictionary =[[NSMutableDictionary alloc] init];
        [recieveDictionary setObject: supplierCategories forKey:@"SupplierCategories"];
        //添加商店类型到本地数据库
        //        [fmdbSupplierCategoryManager insertSupplierCategory:recieveDictionary];
    }
    //    else{
    //        supplierCategories=[fmdbSupplierCategoryManager getSupplierCategoryForLocal];
    //        recieveDictionary = [[NSMutableDictionary alloc] init];
    //        [recieveDictionary setObject: supplierCategories forKey:@"SupplierCategories"];
    //    }
    CGFloat leftX = 0;
    CGFloat rightX = 160;
    
    CGFloat defaultY=SSiphoneType==0?166:166+IOS5HEIGHT;

    
    for (int i = 0; i < [supplierCategories count]; i++) {
        SupplierCategory *supplierCategory =(SupplierCategory *)[supplierCategories objectAtIndex:i];
        
        CGFloat x = i % 2==0 ? leftX : rightX;
        CGFloat y = defaultY + (i / 2) * 36;
        UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(x,y, 162, 40)];
        
        //不高亮显示
        button.adjustsImageWhenHighlighted=NO;
        //设置按钮内容
        [button setTitle:supplierCategory.supplierCategoryName forState:UIControlStateNormal];
        //商铺类型字体：18  标题1
        //        button.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:18];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //设置按钮tag
        [button setTag:supplierCategory.supplierCategoryId];
        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"supplierCategorieBtnBg" ofType:@"png"];
        [button setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
        
        NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"supplierCategorieBtnBgChange" ofType:@"png"];
        [button setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(showShopBtnDelay:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        //        [view addSubview:goView];
        //        [goView release];
        //使用scrollview的话释放button就无法显示
        
        
    }
    
}

//初始化最近浏览
-(void)initTransactionHistory{
    [topView removeFromSuperview];
    //初始化最近浏览样式
    FMDBTransactionHistory *fmdbTransactionHistory=[[FMDBTransactionHistory alloc]init];
    //    NSArray *tempArray=[[NSArray alloc] initWithArray:[fmdbTransactionHistory getAllHistory]];
    NSArray *transactionHistorys=[fmdbTransactionHistory getAllHistory];
    //    [tempArray release];
    //    NSArray *transactionHistorys=[[NSArray alloc] initWithArray:[fmdbTransactionHistory getAllHistory]];
    
    //添加最新浏览大背景
    topView=[[UIView alloc]init];
    
    topView.frame=CGRectMake(0, 0, 320, SStopViewHeight);
    [bgScrView addSubview:topView];
    //如果没有最近浏览，则显示noHistoryBg图片
    //    if([transactionHistorys objectAtIndex:0] == @"1"){
    //        UIImage *image = [UIImage imageNamed:@"noHistoryBg.png"];
    //        topView.layer.contents = (id) image.CGImage;
    //        // 如果需要背景透明加上下面这句
    ////       topView.layer.backgroundColor = [UIColor clearColor].CGColor;
    //    }
    //    else{
    //最近浏览背景图片
    
    int count=0;
    int indexX=0;
    int indexY=0;
    int tempCount=SSiphoneType==0?2:3;
    
    for(int i=0;i<tempCount;i++){
        if(i==0){
            indexY=6;
        }
        else if(i==1){
            indexY=81;
        }
        else{
            indexY=156;
        }
        for(int j=0;j<4;j++){
            if(j==0){
                indexX=16;
            }
            else{
                indexX=indexX+76;
            }
            UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(indexX,indexY,60,69)];
            NSString *filePath=[[NSBundle mainBundle] pathForResource:@"HistoryBg" ofType:@"png"];
            [imageView setImage:[UIImage imageWithContentsOfFile:filePath]];
            [imageView setUserInteractionEnabled:YES];
            [topView addSubview:imageView];
            if([transactionHistorys objectAtIndex:count]==ISNULL || [[transactionHistorys objectAtIndex:count] supplierId] == 0){
                //如果没有收藏商铺
                UIImageView* addImg=[[UIImageView alloc] initWithFrame:CGRectMake(indexX,indexY,60,69)];
                NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"HistoryBgNil" ofType:@"png"];
                [addImg setImage:[UIImage imageWithContentsOfFile:filePath2]];
                [addImg setUserInteractionEnabled:YES];
                [topView addSubview:addImg];
            }
            else
            {
                //如果有收藏商铺
                //添加图片和名称
                //图片
                UICustomImageView *supplierImg=[[UICustomImageView alloc] initWithFrame:CGRectMake(1,4,58,46)];
                UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                imgBtn.frame=CGRectMake(0, 0, 60, 69);
                [imgBtn setShowsTouchWhenHighlighted:YES];
                [imgBtn setTag:[[transactionHistorys objectAtIndex:count] supplierId]];
                
                [imgBtn addTarget:self action:@selector(showDetailShopDelay:) forControlEvents:UIControlEventTouchUpInside];
                //有商铺图片
                [supplierImg setContentMode:UIViewContentModeScaleAspectFit];
                [supplierImg setUserInteractionEnabled:YES];
                [supplierImg setImage:nil];
                [supplierImg setImageURL:[[transactionHistorys objectAtIndex:count] imgUrl]];
                
                
                UILabel *supplierNameLab=[[UILabel alloc]initWithFrame:CGRectMake(3, 50, 54, 15)];
                //修改店铺长度为4
                if([[transactionHistorys objectAtIndex:count] supplierName].length>4){
                    NSString *supplierNameShort = [[[transactionHistorys objectAtIndex:count] supplierName] substringToIndex:4];
                    [[transactionHistorys objectAtIndex:count] setSupplierName:supplierNameShort];
                }
                supplierNameLab.text=[[transactionHistorys objectAtIndex:count] supplierName];
                supplierNameLab.font=[UIFont fontWithName:@"Helvetica-Bold" size:12];
                supplierNameLab.textAlignment = UITextAlignmentCenter;
                supplierNameLab.backgroundColor = [UIColor clearColor];
                supplierNameLab.textColor = [UIColor whiteColor];
                
                [imageView addSubview:supplierImg];
                [imageView addSubview:imgBtn];
                [imageView addSubview:supplierNameLab];
            }
            count++;
        }
    }
    //    }
    //    [topView release];
}

//修改搜索栏取消按钮内容和样式
- (void)searchBarTextDidBeginEditing:(UISearchBar *)hsearchBar
{
    hsearchBar.showsCancelButton = YES;
    for(id cc in [hsearchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setBackgroundColor:[UIColor clearColor]];
            NSString *filePath=[[NSBundle mainBundle] pathForResource:@"cancelBtnBg" ofType:@"png"];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateHighlighted];
            [btn setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(cancelInput:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
            //文字大小 内容1
            //            btn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
        }
    }
}
//直接搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //创建新的试图并将试图推入栈中
    //    if (searchShopListController != nil) {
    //        [searchShopListController release];
    //        searchShopListController = nil;
    //    }
    SearchShopListController *searchShopListController = [[SearchShopListController alloc]init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
    searchShopListController.searchType=@"0";//进入直接搜索
    searchShopListController.conditions=[searchBar text];//直接搜索条件
    [dictionary setObject:@"mainPageSearch" forKey:@"source"];
    [searchShopListController setRecieveDictionary:dictionary];
    [self.navigationController pushViewController: searchShopListController animated:YES];
}

//显示广告信息
- (IBAction)showAd:(id)sender {
    NSInteger textId=[sender tag];
    NSString *adIdForTag = [[NSString alloc] initWithFormat:@"%d", textId];
    Ad *ad=[fmdbAdManager getAdForId:adIdForTag];
    //统计广告点击信息到友盟
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          ad.type,@"广告类型",ad.value,@"广告VALUE值", nil];
    [MobClick event:@"mainPageAdNew" attributes:dict];
    if([ad.type isEqualToString:@"网页广告"]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ad.value]];
    }
    if([ad.type isEqualToString:@"推荐商家"]){
        if(isTouched){
            isTouched=NO;
            //创建新的试图并将试图推入栈中
            DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
            [dictionary setObject:ad.value forKey:@"supId"];
            [detailShopViewController setRecieveDictionary:dictionary];
            [self.navigationController pushViewController: detailShopViewController animated:YES];
        }
    }
}

//设置时间
-(void)scrollTimer{
    timeCount ++;
    if (timeCount == adsCount) {
        timeCount = 0;
    }
    [scrollView scrollRectToVisible:CGRectMake(timeCount * 320.0, 65.0, 320.0, 60.0) animated:YES];
}

//初始化广告
-(void)initAd
{
    AdManager *adManager=[[AdManager alloc]init];
    fmdbAdManager=[[FMDBAdManager alloc] init];
    
    if([appDelegate status]){
        ads=[adManager getSupplierByPosition:@"首页"];
        //插入到本地
        [fmdbAdManager insertAd:ads position:@"首页"];
        
    }
    //    else{
    //        ads=[fmdbAdManager getAdForPosition:@"首页"];
    //    }
    //广告图大小320*60
    // Create the scroll view and set its content size and delegate
    //小图
    //    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 371.0f, 320.0f, 120.0f)];
    //大图
    CGFloat defaultY=SSiphoneType==0?351.0f:351.0f+IOS5HEIGHT;
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,defaultY, 320.0f, 120.0f)];
    scrollView.contentSize = CGSizeMake([ads count] * 320.0f, scrollView.frame.size.height);//3张图片
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    adsCount=[ads count];
    //load the scroll view
    for (int i = 0; i < [ads count]; i++) {
        UICustomImageView *adImageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(i * 320.0f,  0.0f, 320.0f, 60.0f)];
        [adImageView setContentMode:UIViewContentModeScaleAspectFit];
        [adImageView setUserInteractionEnabled:YES];
        adImageView.tag=900+i;
        [adImageView setImage:nil];
        [adImageView setImageURL:((Ad *)[ads objectAtIndex:i]).imgUrl];
        UIButton *adImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        adImgBtn.frame=CGRectMake(i * 320.0f,  0.0f, 320.0f, 60.0f);
        [adImgBtn setTag:((Ad *)[ads objectAtIndex:i]).adId];
        //        adImgBtn.backgroundColor = [UIColor clearColor];
        [adImgBtn addTarget:self action:@selector(showAd:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:adImageView];
        [scrollView addSubview:adImgBtn];
    }
    [self.view addSubview:scrollView];
    timeCount = 0;
    //    [ads release];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
}




- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置视图title
    self.title=@"首页";
    //判断网络是否连接
    NetWorkManager *netWorkManager=[[NetWorkManager alloc]init];
    //初始化代理
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
	//获得连接状态
    appDelegate.status=[netWorkManager netWorkStatus];
    
    if([appDelegate status]){
        //    supplierManager=[[SupplierManager alloc]init];
        
        //初始化本地商铺类型管理
        //    fmdbSupplierCategoryManager=[[FMDBSupplierCategoryManager alloc]init];
        //初始化本地商铺管理
        //    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
        //初始化数据库，创建表
        FMDBManager *fmdbManager=[[FMDBManager alloc]init];
        [fmdbManager initDataBase];
        
        //设置view为白色背景
        [self.view setBackgroundColor:[UIColor whiteColor]];
        //初始化索搜栏
        [self initSearchBar];
        //初始化滚动背景
        [self initScrollView];
        //初始化店铺类型按钮
        [self setSuppierCategoryBtn:bgScrView];
        //初始化广告位
        [self initAd];
        
        [PublicFunction CreateImageFolder];
        //设置搜索页面的值
        NSMutableDictionary *dictionary=[NSMutableDictionary dictionaryWithCapacity:1];
        [dictionary setObject:supplierCategories forKey:@"SupplierCategories"];
        [appDelegate setRecieveDictionary:dictionary];
    }
    else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请连接网络" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    


}

- (void)viewWillAppear:(BOOL)animated{
    //隐藏导航栏
    self.navigationController.navigationBarHidden=YES;
    //初始化最近浏览，每次都运行一次，用于刷新最近浏览
    [self initTransactionHistory];
    isTouched=YES;
}

- (IBAction)showShopBtnDelay:(id)send
{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self performSelector:@selector(showShopBtn:) withObject:send afterDelay:0.1];
}

//显示商家列表信息
-(IBAction)showShopBtn:(id)send{
    if(isTouched){
        isTouched=NO;
        //创建新的试图并将试图推入栈中
        ShopListController *shopListController= [[ShopListController alloc]init];
        supTypeId=[[NSString alloc]initWithFormat:@"%d", [send tag]];
        //传递tag值，商家类型id
        appDelegate.supId=supTypeId;
        NSMutableDictionary *dictionary=[NSMutableDictionary dictionaryWithCapacity:2];
        [dictionary setObject:supplierCategories forKey:@"SupplierCategories"];
        NSString *supTypeName = [send titleForState:(UIControlStateNormal)];
        [dictionary setObject:supTypeName forKey:@"supTypeName"];
        [dictionary setObject:@"mainPageSupType" forKey:@"source"];//用户统计到友盟时的来源判断
        [shopListController setRecieveDictionary:dictionary];
        
        [self.navigationController pushViewController: shopListController animated:YES];
    }
}

- (IBAction)showDetailShopDelay:(id)sender {
    //第一步创建一个声音的路径
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    //第二步：申明一个sound id对象
    SystemSoundID system_sound_id;
    //第三步：通过AudioServicesCreateSystemSoundID方法注册一个声音对象
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self performSelector:@selector(showDetailShop:) withObject:sender afterDelay:0.1];
}

//显示商家详细信息
- (IBAction)showDetailShop:(id)sender {
    if(isTouched){
        isTouched=NO;
        supIdToString=[[NSString alloc]initWithFormat:@"%d", [sender tag]];
        //创建新的试图并将试图推入栈中
        DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
        [dictionary setObject:supIdToString forKey:@"supId"];
        [dictionary setObject:@"mainPageHistoryBtnClickedNew" forKey:@"source"];//用户统计到友盟时的来源判断
        [detailShopViewController setRecieveDictionary:dictionary];
        [self.navigationController pushViewController: detailShopViewController animated:YES];
    }
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)viewDidUnload
{
    self.supplierCategories=nil;
    self.appDelegate=nil;
    self.searchBarCustom=nil;
    self.bgScrView=nil;
    self.topView=nil;
    self.scrollView=nil;
    self.fmdbAdManager=nil;
    self.ads=nil;
    self.supIdToString=nil;
    self.supTypeId=nil;
    [super viewDidUnload];
}

- (void)viewDidDisappear:(BOOL)animated{
    searchBarCustom.text=@"";
    [searchBarCustom resignFirstResponder];
}

//使用arc不需要重载dealloc，如果是释放对象内存以外的处理，是可以重载函数的，但是不可以调用[super delloc]
//- (void)dealloc {
//
//}
@end

